package com.opo5.logisticsmanagement.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opo5.logisticsmanagement.common.R;
import com.opo5.logisticsmanagement.dao.DepartmentDao;
import com.opo5.logisticsmanagement.dao.UserDao;
import com.opo5.logisticsmanagement.domain.Department;
import com.opo5.logisticsmanagement.domain.User;
import com.opo5.logisticsmanagement.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author lixin
* @description 针对表【tbs_department】的数据库操作Service实现
* @createDate 2022-07-10 08:57:37
*/
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentDao, Department>
    implements DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private UserDao userDao;

    @Override
    public R getDeptByCondition(String departmentname, Integer currentPage, Integer pageSize) {
        Page<Department> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(departmentname!=null,"departmentname",departmentname);
        departmentDao.selectPage(page, queryWrapper);
        List<Department> departments = page.getRecords();
        return R.success(new R().add("depts",departments).add("total",page.getTotal()).getMap());
    }

    @Override
    public R getUserById(Integer id) {
        Department department = departmentDao.selectById(id);
        return R.success(department);
    }

    @Override
    public R addDept(Department department) {
        int flag = departmentDao.insert(department);
        if (flag==1){
            return R.success(null);
        }
        return R.error("添加部门信息失败");
    }

    @Override
    public R editDept(Department department) {
        int flag = departmentDao.updateById(department);
        if (flag==1){
            return R.success(null);
        }
        return R.error("修改部门信息失败");
    }

    @Override
    public R delDept(Integer[] ids) {
        int i = 0;
        for(Integer id : ids){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dept_id",id);
            Integer count = userDao.selectCount(queryWrapper);
            if (count.equals(0)){
                departmentDao.deleteById(id);
                i++;
            }
        };
        if(i != ids.length){
            return R.error("删除了"+i+"条,"+"失败"+(ids.length-i)+"条");
        }
        return R.success(null);
    }

    @Override
    public List<Department> getDeptAll() {
        List<Department> departments = departmentDao.selectList(null);
        return departments;
    }

}




